package com.lin.controller;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RequestMapping("/demo4")
@Controller
public class Demo4 {

    @Value("${queue.demo4_exchange_name}")
    public String EXCHANGE_NAME;
    /*
     * 前面我们只是简单的使用了fanout交换机，还有很多其他类型的交换机可以实现更多的功能比如消息的“路由”哦
     * 这节我们使用direct类型的叫环节来实现 “匹配”路由交换机
     */
    // localhost:8080/demo4/log/normal
    @RequestMapping("/log/{log_level}")
    @ResponseBody
    public String Log(@PathVariable String log_level) {
        try(
                Connection connection = RabbitUtil.getConnection();
                Channel channel = connection.createChannel();
                ) {
            channel.exchangeDeclare(EXCHANGE_NAME,"direct");
            String message = log_level + " " + new Date().toString() + ": 林渊日志";
            channel.basicPublish(EXCHANGE_NAME,log_level, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "发布日志成功";
    }
}
